﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace MVCCornucopia.Common
{
    public class PhoneNumberAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public PhoneNumberAttribute()
            : base(@"^[2-9]\d{2}-\d{3}-\d{4}$")
        {
            ErrorMessage = "Enter a valid phone number!";
        }


        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
            ModelMetadata metadata, ControllerContext context)
        {

            return new List<ModelClientValidationRule> {
                new ModelClientValidationRegexRule(this.ErrorMessage, this.Pattern),
                new ModelClientValidationRule {
                    ValidationType = "required",
                    ErrorMessage = this.ErrorMessage
                }
            };
        }

        public class ModelClientValidationRegexRule : ModelClientValidationRule
        {
            public ModelClientValidationRegexRule(string errorMessage,
                   string pattern)
            {
                ErrorMessage = errorMessage;
                ValidationType = "regex";
                ValidationParameters.Add("pattern", pattern);
            }
        }


    }
}